package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.pojo.StorageRecord;
import com.bdqn.pojo.Supplier;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.StorageRecordService;
import com.bdqn.service.StorageRecordService;
import com.bdqn.service.StorageRecordServiceImpl;
import com.bdqn.service.StorageRecordServiceImpl;
import com.bdqn.service.SupplierService;
import com.bdqn.service.SupplierServiceImpl;
import com.bdqn.util.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 入库功能模块控制类
 *
 */
@WebServlet("/storageRecord")
public class StorageRecordController extends HttpServlet {
    private StorageRecordService storageRecordService = new StorageRecordServiceImpl();
    private SupplierService supplierService = new SupplierServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        String opr = request.getParameter("opr");
        switch (opr) {
            case "list":
                //查询列表
                list(request, response);
                break;
            case "toAdd":
                //跳转到新增页面
                List<Supplier> supplierList = supplierService.list();
                request.setAttribute("supplierList", supplierList);//所有供货商
                request.getRequestDispatcher("WEB-INF/jsp/storageRecord/add.jsp").forward(request, response);
                break;
            case "add":
                //新增
                add(request,response);
                break;
            case "del"://删除
                del(request,response);
                break;
            case "view"://查询详情信息
                view(request,response);
                break;
            case "toUpdate"://进入道修改页面
                toUpdate(request,response);
                break;
            case "update"://修改
                update(request,response);
                break;
        }
    }

    /**
     * 新增
     */
    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String srCode = request.getParameter("srCode");//入库编号
        String goodsName = request.getParameter("goodsName");//商品名称
        String goodsCountStr = request.getParameter("goodsCount");//入库数量
        double goodsCount = goodsCountStr==null?0: Double.parseDouble(goodsCountStr);
        String goodsUnit = request.getParameter("goodsUnit");//入库单位
        String totalAmountStr = request.getParameter("totalAmount");//总金额
        double totalAmount = totalAmountStr==null?0: Double.parseDouble(totalAmountStr);
        String supplierIdStr = request.getParameter("supplierId");//供货商
        int supplierId = supplierIdStr==null?0: Integer.parseInt(supplierIdStr);
        String payStatusStr = request.getParameter("payStatus");//支付状态
        int payStatus = payStatusStr==null?0: Integer.parseInt(payStatusStr);
        SysUser addSysUser = (SysUser) request.getSession().getAttribute("USER_SESSION");//新增者
        StorageRecord storageRecord = new StorageRecord();
        storageRecord.setSrCode(srCode);
        storageRecord.setGoodsCount(goodsCount);
        storageRecord.setGoodsName(goodsName);
        storageRecord.setGoodsUnit(goodsUnit);
        storageRecord.setTotalAmount(totalAmount);
        storageRecord.setSupplierId( supplierId);
        storageRecord.setPayStatus( payStatus);
        storageRecord.setCreatedUserId(addSysUser.getId());
        int add = storageRecordService.add(storageRecord);
        if(add == 1){
            //新增成功
            list(request,response);
        }else {
            //新增失败
            request.getRequestDispatcher("WEB-INF/jsp/storageRecord/add.jsp").forward(request,response);
        }
    }

    /**
     * 分页查询
     */
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getContextPath();
        System.out.println(path);
        Page<StorageRecord> page = new Page<>();
        String goodName = request.getParameter("queryGoodsName");//商品名称
        String querySupplierIdStr = request.getParameter("querySupplierId");//供货商ID
        int querySupplierId = (querySupplierIdStr == null ||"".equals(querySupplierIdStr)) ? 0: Integer.parseInt(querySupplierIdStr);
        String queryPayStatusStr = request.getParameter("queryPayStatus");//付款状态
        int queryPayStatus = (queryPayStatusStr == null ||"".equals(queryPayStatusStr))? 0: Integer.parseInt(queryPayStatusStr);
        String currPageNoStr = request.getParameter("pageIndex");//查询页码
        int currPageNo = currPageNoStr == null ? 1: Integer.parseInt(currPageNoStr);
        page.setTotalCount(storageRecordService.count(goodName,querySupplierId,queryPayStatus));
        page.setCurrPageNo(currPageNo);
        int pageNo = (page.getCurrPageNo() - 1) * page.getPageSize();//查询下标
        List<StorageRecord> storageRecordList = storageRecordService.selectPageList(pageNo, page.getPageSize(),goodName,querySupplierId,queryPayStatus);//查询结果
        List<Supplier> supplierList = supplierService.list();
        request.setAttribute("queryGoodsName", goodName);//商品名称
        request.setAttribute("querypayStatus", queryPayStatus);//付款状态
        request.setAttribute("querySupplierId", querySupplierId);//供货商id
        request.setAttribute("supplierList", supplierList);//所有供货商
        request.setAttribute("storageRecordList", storageRecordList);//查询出来的入库信息
        request.setAttribute("totalPageCount", page.getTotalPageCount());//总页数
        request.setAttribute("totalCount", page.getTotalCount());//总记录数
        request.setAttribute("currentPageNo", page.getCurrPageNo());//当前页码
        request.getRequestDispatcher("WEB-INF/jsp/storageRecord/list.jsp").forward(request, response);
    }

    /**
     * 根据ID删除入库
     */
    private void del(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String idStr = request.getParameter("storageRecordId");//指定删除的id
        int id = idStr == null?0: Integer.parseInt(idStr);
        StorageRecord storageRecord = storageRecordService.getStorageRecord(id);
        String delResult = "notexist";//默认用户不存在
        if(storageRecord!=null) {
            int del = storageRecordService.delete(id);
            System.out.println(del);
            delResult = del == 1 ? "true" : "false";
        }
        Map<String,String> map = new HashMap<>();
        map.put("delResult",delResult);
        // 将对象转换为JSON格式
        String resultJson = JSON.toJSONString(map);
        System.out.println(resultJson);
        response.getWriter().print(resultJson);
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * 查询详情信息
     */
    private void view(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("storageRecordId");//指定查询的id
        int id = idStr == null?0: Integer.parseInt(idStr);
        StorageRecord storageRecord = storageRecordService.getStorageRecord(id);
        request.setAttribute("storageRecord",storageRecord);
        request.getRequestDispatcher("WEB-INF/jsp/storageRecord/view.jsp").forward(request, response);
    }

    /**
     * 进入道修改页面
     */
    private void toUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("storageRecordId");//指定查询的id
        int id = idStr == null?0: Integer.parseInt(idStr);
        StorageRecord storageRecord = storageRecordService.getStorageRecord(id);
        List<Supplier> supplierList = supplierService.list();
        request.setAttribute("supplierList", supplierList);//所有供货商
        request.setAttribute("storageRecord",storageRecord);
        request.getRequestDispatcher("WEB-INF/jsp/storageRecord/update.jsp").forward(request, response);
    }

    /**
     * 修改
     */
    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取道修改信息
        String idStr= request.getParameter("id");//修改商品ID
        int id = idStr==null?0:Integer.parseInt(idStr);
        String goodsName= request.getParameter("goodsName");//商品名称
        String goodsUnit= request.getParameter("goodsUnit");//商品单位
        String goodsCountStr= request.getParameter("goodsCount");//入库数量
        double goodsCount = goodsCountStr==null?0: Double.parseDouble(goodsCountStr);
        String totalAmountStr= request.getParameter("totalAmount");//总金额
        double totalAmount = totalAmountStr==null?0: Double.parseDouble(totalAmountStr);
        String supplierIdStr= request.getParameter("supplierId");//供货商
        String payStatusStr= request.getParameter("payStatus");//支付状态
        int payStatus= payStatusStr==null?0:Integer.parseInt(payStatusStr);
        int supplierId = supplierIdStr==null?0:Integer.parseInt(supplierIdStr);
        SysUser upSysUser = (SysUser) request.getSession().getAttribute("USER_SESSION");   //更新者
        StorageRecord storageRecord = new StorageRecord(id,goodsName,goodsUnit,goodsCount,totalAmount,supplierId,upSysUser.getId(),payStatus);
        int upd = storageRecordService.update(storageRecord);
        if(upd==1){
            //修改成功
            list(request,response);
        }else {
            //修改失败
            request.getRequestDispatcher("WEB-INF/jsp/storageRecord/update.jsp").forward(request,response);
        }
    }
}
